<?php
// 注册处理脚本
require_once 'db_config.php';

// 检查请求方法是否为POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取表单数据
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $confirmPassword = trim($_POST['confirmPassword'] ?? '');
    
    $errors = [];
    
    // 验证用户名
    if (empty($username)) {
        $errors['username'] = '请输入用户名';
    } elseif (strlen($username) < 4 || strlen($username) > 16) {
        $errors['username'] = '用户名长度应为4-16个字符';
    } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
        $errors['username'] = '用户名只能包含字母、数字和下划线';
    }
    
    // 验证邮箱
    if (empty($email)) {
        $errors['email'] = '请输入邮箱';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = '请输入有效的邮箱地址';
    }
    
    // 验证密码
    if (empty($password)) {
        $errors['password'] = '请输入密码';
    } elseif (strlen($password) < 8 || strlen($password) > 20) {
        $errors['password'] = '密码长度应为8-20个字符';
    } elseif (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/', $password)) {
        $errors['password'] = '密码必须包含大小写字母、数字和特殊字符';
    }
    
    // 验证确认密码
    if (empty($confirmPassword)) {
        $errors['confirmPassword'] = '请确认密码';
    } elseif ($password !== $confirmPassword) {
        $errors['confirmPassword'] = '两次输入的密码不一致';
    }
    
    // 如果有错误，返回JSON错误信息
    if (!empty($errors)) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'errors' => $errors]);
        exit;
    }
    
    // 检查用户名或邮箱是否已存在
    $checkSql = "SELECT id FROM users WHERE username = ? OR email = ?";
    $checkStmt = $conn->prepare($checkSql);
    $checkStmt->bind_param("ss", $username, $email);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    
    if ($checkResult->num_rows > 0) {
        $existingUser = $checkResult->fetch_assoc();
        // 检查用户名是否已存在
        $checkUsernameSql = "SELECT id FROM users WHERE username = ?";
        $checkUsernameStmt = $conn->prepare($checkUsernameSql);
        $checkUsernameStmt->bind_param("s", $username);
        $checkUsernameStmt->execute();
        $usernameResult = $checkUsernameStmt->get_result();
        
        if ($usernameResult->num_rows > 0) {
            $errors['username'] = '用户名已被注册';
        }
        
        // 检查邮箱是否已存在
        $checkEmailSql = "SELECT id FROM users WHERE email = ?";
        $checkEmailStmt = $conn->prepare($checkEmailSql);
        $checkEmailStmt->bind_param("s", $email);
        $checkEmailStmt->execute();
        $emailResult = $checkEmailStmt->get_result();
        
        if ($emailResult->num_rows > 0) {
            $errors['email'] = '邮箱已被注册';
        }
        
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'errors' => $errors]);
        exit;
    }
    
    // 密码哈希处理
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    
    // 插入新用户到数据库
    $insertSql = "INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)";
    $insertStmt = $conn->prepare($insertSql);
    $insertStmt->bind_param("sss", $username, $email, $passwordHash);
    
    if ($insertStmt->execute()) {
        // 注册成功
        header('Content-Type: application/json');
        echo json_encode([
            'status' => 'success',
            'message' => '注册成功，请登录',
            'redirect' => 'index.html'
        ]);
        exit;
    } else {
        // 数据库错误
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => '注册失败，请稍后重试']);
        exit;
    }
} else {
    // 不是POST请求
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => '无效的请求方法']);
    exit;
}
?>
